<?php
namespace app\houtai\controller\user;
use app\houtai\controller\BaseController;
use think\Db;
use think\Process;
use think\Request;
use think\db\Expression;

class AgentController extends BaseController {
    /**
     *  @brief  : 重定向到微信后台
     *  @return : redirect
     *  @details:
     */
    public function wxhdAction() {
        $uid = $this->request->param('uid/d', 0);
        $sec = time() - 0 * 60;
        $str = $uid.'|'.date('YmdHi', $sec);
        $eax = encrypt($str);
        $url = config('wei_xin_hd_url');
        dump($url);die;
        $url = trim($url, '/');
        return $this->redirect("{$url}/Default.aspx?data={$eax}");
    }
    /**
     *  @brief  :代理管理-推广员返点结算
     *  @return : page
     *  @details:
     */
    public function indexAction() {
        $conds = ['a.UserID' => ['GT', 0]];
        $conds['a.Status'] = ['neq', 0];
        $conds_channel = [];
        $order = [];
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', key(array_slice($CHANNELS, 0, 1, true)));
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds_channel[] = ['IN', array_keys($CHANNELS)];
            $conds_channel[] = ['EQ', $channel];
        } else {
            $conds_channel = ['IN', array_keys($CHANNELS)];
        }
        $conds['a.Channel'] = $conds_channel;
        ////////////////////////////////////////
        $DisableLogin = $this->request->param('DisableLogin/d', 0);
        $DisableLogin = in_array($DisableLogin, [0, 1, 2]) ? $DisableLogin : 0;
        if (in_array($DisableLogin, [0, 1])) {
            $conds['a.DisableLogin'] = $DisableLogin; // 0=允许登陆; 1=禁止登陆;
        }
        $orderMap = [
            'A' => 'ID',
            'D' => 'AgentLevel',
            'M' => 'RebateTime',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'A';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
///////////////////////
        $list = table('CYWebSMSDB.dbo.AgentReg a', 'rydb.websms')->field([
            'a.*',
            '(SELECT COUNT(b.UserID) FROM [CYBasicDB].[dbo].[AccountsInfo] b WHERE b.SpreaderID = a.[UserID])' => 'BindCount',
            "( CASE IsDirect WHEN 1 THEN '直销' ELSE ( CASE AgentLevel WHEN 1 THEN '一级' WHEN 2 THEN '二级' WHEN 3 THEN '三级' WHEN 4 THEN '四级' WHEN 5 THEN '五级' WHEN 6 THEN '六级' WHEN 7 THEN '七级' ELSE '默认' END ) END )"=>'AgentLevelName',
            'ISNULL((SELECT SUM(c.[RMB])      FROM [CYWebSMSDB].[dbo].[AgentChargeRebate] c WHERE c.[AgentID]=a.[UserID] and c.[Addtime]>a.[RebateTime] and c.myAgentLevel=a.AgentLevel),0)' => 'Rebate',
            'ISNULL((SELECT SUM(c.[myRebate]) FROM [CYWebSMSDB].[dbo].[AgentChargeRebate] c WHERE c.[AgentID]=a.[UserID] and c.[Addtime]>a.[RebateTime] and c.myAgentLevel=1),0)' => 'RebateMax0',
            'ISNULL((SELECT SUM(c.[myRebate]) FROM [CYWebSMSDB].[dbo].[AgentChargeRebate] c WHERE c.[AgentID]=a.[UserID] and c.[Addtime]>a.[RebateTime] and c.myAgentLevel=2),0)' => 'RebateMax1',
            'ISNULL((SELECT SUM(c.[myRebate]) FROM [CYWebSMSDB].[dbo].[AgentChargeRebate] c WHERE c.[AgentID]=a.[UserID] and c.[Addtime]>a.[RebateTime] and c.myAgentLevel=3),0)' => 'RebateMax2',
            'ISNULL((SELECT SUM(c.[myRebate]) FROM [CYWebSMSDB].[dbo].[AgentChargeRebate] c WHERE c.[AgentID]=a.[UserID] and c.[Addtime]>a.[RebateTime]),0)'=> 'myRebate2',
        ])->where($conds)->order($order)->select();
        //分页条数
        $total= count($list);
        $path = Request::instance()->baseUrl();
        $page = new \org\dtcms($list, $total <= 0 ? 1 : $total, 1, $total, false, ['path' => $path]);
        echo "<pre/>";
        print_r($page);die;
        $tree = list_to_tree($list, 'UserID', 'ParentId', '_child', 0);
        ////////////////////////////////////////////////////////////////////////////
        // 订单去重
        $sql2 = table('CYWebSMSDB.dbo.ChargeOnline a', 'rydb.websms')
            ->field(['b.Channel', 'a.MerBillNo', 'SUM(DISTINCT a.RMB)' => 'RMB'])
            ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID = a.UserID', 'LEFT')
            ->where(['a.Status' => 1, 'a.GameStatus' => 1])
            ->group('b.Channel,a.MerBillNo')
            ->buildSql();
        $sql2 = sql_pure($sql2);
        // 渠道总充值
        $sql2 = table("{$sql2} c", 'rydb.websms')->field(['c.Channel', 'SUM(c.RMB)' => 'a'])->group('c.Channel')->buildSql();
        $sql2 = sql_pure($sql2);
        // 渠道总返点
        $sql3 = table('CYWebSMSDB.dbo.AgentChargeRebate a', 'rydb.websms')
            ->field(['b.Channel', 'SUM(a.myRebate)' => 'b'])
            ->join('CYWebSMSDB.dbo.AgentReg b', 'b.UserID = a.AgentID', 'LEFT')
            ->where(['a.IsDisable' => 0])
            ->group('b.Channel')
            ->buildSql();
        $sql3 = sql_pure($sql3);

        // 同时查询渠道总充值&总返点
        $Total = table("{$sql2} m", 'rydb.websms')
            ->field(['m.Channel', 'ISNULL(m.a, 0)' => 'Charge', 'ISNULL(n.b, 0)' => 'Rebate'])
            ->join("{$sql3} n", 'n.Channel = m.Channel', 'FULL OUTER')
            ->where(['m.Channel' => $conds_channel])
            ->find();
        // 公众号提现佣金池
        $CashPool = 0;
        $eax = config("share.{$channel}");
        $eax = empty($eax['gzh_key']) ? '' : $eax['gzh_key'];
        $eax = empty($eax) ? [] : config("wxgzh.{$eax}");
        if (!empty($eax['AppID'])) {
            $CashPool = table('WxGzh', 'rydb.websms')->where('AppID', $eax['AppID'])->value('CashPool');
        }

        $dddd = table('CYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
            ->join('CYWebSMSDB.dbo.AgentChargeRebate c', 'c.AgentID = a.UserID', 'LEFT')
            ->where($conds)
            ->where('c.myAgentLevel', 'EXP', '= a.AgentLevel')
            ->where('c.Addtime', 'EXP', '> a.RebateTime')
            ->sum('c.RMB');

        $eeee = table('CYWebSMSDB.dbo.AgentReg a', 'rydb.websms')
            ->join('CYWebSMSDB.dbo.AgentChargeRebate c', 'c.AgentID = a.UserID', 'LEFT')
            ->where($conds)
            ->where('c.Addtime', 'EXP', '> a.RebateTime')
            ->sum('c.myRebate');
            //dump($tree);die;
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'channel'   => $channel,
            'CHANNELS'  => $CHANNELS,
            'tree'  => $tree,
            'page'  => $page,
            'Total' => $Total,
            'CashPool'  => $CashPool,
            'dddd' => $dddd,
            'eeee' => $eeee,
            'DisableLogin' => $DisableLogin,
        ]);
    }
    /**
     *  @brief  : 结算
     *  @return : JSON
     *  @details:
     */
    public function jiesuanAction() {
        if (!$this->request->isPost()) {
            return result([], 100, '非法请求');
        }
        $AUID = $this->request->param('UserID/d', 0);
        if ($AUID <= 0) {
            return result([], 101, '业务参数无效');
        }

        $Agent = table('AgentReg a', 'rydb.websms')->field([
            'a.ID', 'a.UserID', 'a.Compellation', 'a.OpenID', 'a.RebateRMB', 'a.RebateTime',
            'ISNULL(( SELECT SUM (c.myRebate) FROM AgentChargeRebate c WHERE c.AgentID = a.UserID AND c.Addtime > a.RebateTime), 0)'=>'myRebate2',
        ])->where(['a.UserID'=>$AUID])->find();

        if(empty($Agent)){
            return result([], 102, '用户不存在');
        }

        if ($Agent['myRebate2'] == 0) {
            return result([], 103, '结算失败! 结算金额为空或为零!');
        }

        trace("后台结算代理[{$Agent['UserID']}][{$Agent['Compellation']}][{$Agent['RebateTime']}][{$Agent['RebateRMB']}]");

        table('AgentRebate', 'rydb.websms')->insert([
            'UserID'      => $AUID,
            'RMB'         => $Agent['myRebate2'],
            'CollectDate' => new Expression('GETDATE()'),
            'Remarks'     => '后台结算',
        ]);

        table('AgentReg', 'rydb.websms')->where(['ID'=>$Agent['ID']])->update([
            'RebateTime'  => new Expression('GETDATE()'),
            'RebateRMB'   => $Agent['myRebate2'],
        ]);
        return result([], 0, "结算成功, 结算金额:{$Agent['myRebate2']}");
    }
    /**
     *  @brief  : 用户管理-推广员注册
     *  @return : page
     *  @details:
     */
    public function regAction() {
        $conds = [];
        $order = [];
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $state = $this->request->param('state/d', -1);
        if (in_array($state, [0, 1])) {
            $conds['a.Status'] = $state;
        }
        /////////////////////////////////
        $time1 = $this->request->param('time1/s', '', 'trim');
        $time2 = $this->request->param('time2/s', '', 'trim');

        $aa = YmdHis2Unix($time1);
        $bb = YmdHis2Unix($time2);
        $ta = date('Y-m-d 00:00:00', $aa);
        $tb = date('Y-m-d 23:59:59', $bb);
        if ($aa > 0) {
            if ($bb > 0) {
                if ($aa <= $bb) {
                    $conds['a.Addtime'] = ['BETWEEN TIME', [$ta, $tb]];
                } else {
                    $conds['a.Addtime'] = ['>= TIME', $ta];
                }
            } else {
                $conds['a.Addtime'] = ['>= TIME', $ta];
            }
        } else {
            if ($bb > 0) {
                $conds['a.Addtime'] = ['<= TIME', $tb];
            }
        }
        /////////////////////////////////
        $search = $this->request->param('search/s', '', 'trim');
        if (!empty($search)) {
            if ($search > 0 ) {
                $conds['a.UserID|a.GameID'] = $search;
            }else{
                $conds['a.Compellation|a.PassPortID'] = ['LIKE', "%{$search}%"];
            }
        }
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['a.Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['a.Channel'][] = ['EQ', $channel];
        } else {
            $conds['a.Channel'] = ['IN', array_keys($CHANNELS)];
        }
        ////////////////////////////////////////////////////////////////////////////
        $orderMap = [
            'A' => 'Channel',
            'B' => 'ID',
            'C' => 'UserID',
            'D' => 'GameID',
            'E' => 'Compellation',
            'F' => 'BindCount',
            'G' => 'PassPortID',
            'H' => 'MobilePhone',
            'I' => 'LogonPass',
            'J' => 'Addtime',
            'K' => 'IP',
            'L' => 'Status',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;////////////////////////////////////////////////////////////////////////////
        $list = table('CYWebSMSDB.dbo.AgentReg a', 'rydb.websms')->field([
            'a.ID', 'a.UserID', 'a.GameID', 'a.Compellation', 'a.PassPortID', 'a.MobilePhone',
            'a.WeiXin', 'a.LogonPass', 'a.Addtime', 'a.Status',
            'a.IP', 'a.AgentLevel', 'a.OpenID', 'a.Sex', 'a.Channel',
            '(SELECT COUNT(UserID) FROM [CYBasicDB].[dbo].[AccountsInfo] b WHERE b.SpreaderID > 0 AND b.SpreaderID = a.UserID)'=> 'BindCount',
        ])->where($conds)->order($order)->paginate();
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'CHANNELS'  => $CHANNELS,
            'channel'   => $channel,
            'state' => $state,
            'time1' => $time1,
            'time2' => $time2,
            'list'  => $list,
            'search'  => $search,
        ]);
    }
    /**
     *  @brief  : 推广员注册-同意申请
     *  @return : json
     *  @details:
     */
     public function agreeAction() {
        $id = $this->request->param('id/d', 0);
        if ($id <= 0) {
            return result([], 1, '业务参数非法');
        }
        $Agent = table('AgentReg', 'rydb.websms')->where('ID', $id)->find();
        if (empty($Agent)) {
            return result([], 2, "不存在该推广员[{$id}]");
        }
        if ($Agent['Status'] > 0) {
            return result([], 3, "该推广员[{$id}]已审核通过");
        }
        if (empty($Agent['OpenID'])) {
            $eax = md5(uniqid(mt_rand(), true));
            $Agent['OpenID'] = $eax;
        }
        $usr = CPP_EfficacyOtherPlatform(
            4, // 平台编号, 参考`LOGIN_TYPE`
            md5($Agent['OpenID']), // 不能与玩家账号冲突
            $Agent['OpenID'], //
            $Agent['WeiXin'], // 用户昵称
            $Agent['Sex'], // 用户性别 0=未知; 1=男性; 2=女性;
            $Agent['IP'], // 连接地址
            md5($Agent['OpenID']), // 机器标识
            $Agent['HeadImgUrl'] ?: '', // 微信头像地址
            $Agent['Channel'] // 渠道
        );
        if (isset($usr['errno'])) {
            trace($usr);
            return result([], 4, '创建推广员账号失败!');
        }
        $a = table('AgentReg', 'rydb.websms')->where('ID', $id)->update([
            'OpenID'  => $Agent['OpenID'],
            'Status'  => 1,
            'AgentLevel' => 3,
            'level2' => 10,
            'MenuStr' => 1,
            'RebateTime'=> new Expression('GETDATE()'),
            'Updatetime'=> new Expression('GETDATE()'),
        ]);
        if (!$a){
            return result([], 9,'修改状态失败');
        }
        $b = table('AccountsInfo', 'rydb.accounts')->where('UserID',$Agent['UserID'])->update([
            'AccountsType'  => 1,
            'Compellation'  => $Agent['Compellation'],
            'PassPortID'    => $Agent['PassPortID'],
        ]);
        if (!$b){
            return result([], 10,'修改实名失败');
        }
        table('IndividualDatum', 'rydb.accounts')->where('UserID', $Agent['UserID'])->update([
            'MobilePhone' => $Agent['MobilePhone'],
        ]);


        return result([], 0, '创建帐号成功!');
    }
//    public function agreeAction() {
//        $id = $this->request->param('id/d', 0);
//        if ($id <= 0) {
//            return result([], 1, '业务参数非法');
//        }
//        $Agent = table('AgentReg', 'rydb.websms')->where('ID', $id)->find();
//        if (empty($Agent)) {
//            return result([], 2, "不存在该推广员[{$id}]");
//        }
//        if ($Agent['Status'] > 0) {
//            return result([], 3, "该推广员[{$id}]已审核通过");
//        }
//        if (empty($Agent['OpenID'])) {
//            $eax = md5(uniqid(mt_rand(), true));
//            $Agent['OpenID'] = $eax;
//        }
//        // $RegAgent = table('Family', 'rydb.websms')->where(['AUID'=>$Agent['UserID'],''])
//        $usr = Go_WechatAndSmallTalkLogin(
//            4, // 平台编号, 参考`LOGIN_TYPE`
//            md5($Agent['OpenID']), // 不能与玩家账号冲突
//            $Agent['OpenID'], //
//            $Agent['WeiXin'], // 用户昵称
//            $Agent['Sex'], // 用户性别 0=未知; 1=男性; 2=女性;
//            $Agent['IP'], // 连接地址
//            md5($Agent['OpenID']), // 机器标识
//            $Agent['HeadImgUrl'] ?: '', // 微信头像地址
//            $Agent['Channel'] // 渠道
//        );
//        if (isset($usr['errno'])) {
//            trace($usr);
//            return result([], 4, '创建推广员账号失败!');
//        }
//
//
//        /**
//         * 增加亲友团信息
//         * */
//        $UserID = $Agent['UserID'];
//        $KindID = table('GameKindNote','rydb.websms')->where(['TypeID'=>1])->field(['KindID','KindName'])->select();
//        $Num = count($KindID);
//        $code = table('CodeIdentifier','rydb.websms')->field('Code')->where('FamilyUsed',0)->limit($Num)->select();
//
//        if (empty($code)) {
//            return result([], 5,'系统分配六位群标识失败');
//        }
//        //房卡场
//        for ($i = 0; $i < $Num; $i++) {
//            foreach ($code as $one) {
//                if ($KindID[$i]['ROW_NUMBER'] == $one['ROW_NUMBER']) {
//                    $KindID[$i]['Codes'] = $one['Code'];
//                }
//            }
//            $Family[] =  ['AUID' => $UserID, 'Code' => $KindID[$i]['Codes'], 'Caption' => '[房卡场].[' .$KindID[$i]['KindName']. '].'.$Agent['Compellation'].'的亲友团', 'KindID' => $KindID[$i]['KindID'], 'State' => 1,'FamilyType'=>1];
//        }
//        $inserfamily = table('Family', 'rydb.websms')->insertAll($Family,true);
//        if ($inserfamily != $Num) {
//            return result([], 6,'亲友团增加失败');
//        }
//
//        /*
//         * 添加房间绑定
//         * */
//        $Users = table('Family', 'rydb.websms')->where(['AUID'=>$UserID,'FamilyType'=>'1'])->select();
//        foreach ($Users as $v) {
//            $data[] = table('CodeIdentifier', 'rydb.websms')->where('Code', $v['Code'])->find();
//
//        }
//        for ($i = 0; $i < count($data); $i++) {
//            foreach ($Users as $one) {
//                if ($data[$i]['Code'] == $one['Code']) {
//                    $insertcodeidentifier = table('CodeIdentifier', 'rydb.websms')->where('Code', $one['Code'])->update(['FamilyUsed' => $one['ID']]);
//                }
//            }
//        }
//        if (!$insertcodeidentifier) {
//            return result([], 7,'房间绑定失败');
//        }
//
//        /*
//         * 增加房间权限
//         * */
//        $Users = table('Family', 'rydb.websms')->where(['AUID'=>$UserID,'FamilyType'=>1])->select();
//        foreach ($Users as $v) {
//            $FamilyMember[] =   ['FamilyID' => $v['ID'], 'MemberUID' => $v['AUID'], 'Status' => 1, 'UserRight' => 64, 'IsBlack' => 0, 'IsPass' => 1, 'Gold' => 0];
//        }
//        $inserfamilymember = table('FamilyMember', 'rydb.websms')->insertAll($FamilyMember,true);
//        if (!$inserfamilymember) {
//            return result([], 8,'房间权限绑定失败');
//        }
//        self::Score($Agent,$id);
//
//        $a = table('AgentReg', 'rydb.websms')->where('ID', $id)->update([
//            'OpenID'  => $Agent['OpenID'],
//            'Status'  => 1,
//            'AgentLevel' => 3,
//            'level2' => 10,
//            'MenuStr' => 1,
//            'RebateTime'=> new Expression('GETDATE()'),
//            'Updatetime'=> new Expression('GETDATE()'),
//        ]);
//        if (!$a){
//            return result([], 9,'修改状态失败');
//        }
//        $b = table('AccountsInfo', 'rydb.accounts')->where('UserID', $UserID)->update([
//            'AccountsType'  => 1,
//            'Compellation'  => $Agent['Compellation'],
//            'PassPortID'    => $Agent['PassPortID'],
//        ]);
//        if (!$b){
//            return result([], 10,'修改实名失败');
//        }
//        table('IndividualDatum', 'rydb.accounts')->where('UserID', $UserID)->update([
//            'MobilePhone' => $Agent['MobilePhone'],
//        ]);
//
//
//        return result([], 0, '创建帐号成功!');
//    }
    /**
     *金币场
     */
//    protected function Score($Agent,$id){
//
//        /*
//         * 增加亲友团信息
//         * */
//        $UserID = $Agent['UserID'];
//        $KindID = table('GameKindNote','rydb.websms')->where('TypeID',1)->field(['KindID','KindName'])->select();
//        $Num = count($KindID);
//        $code = table('CodeIdentifier','rydb.websms')->field('Code')->where('FamilyUsed',0)->limit($Num)->select();
//
//        if (empty($code)) {
//            return result([], 12,'系统分配六位群标识失败');
//        }
//        //金币场
//        for ($i = 0; $i < count($KindID); $i++) {
//            foreach ($code as $one) {
//                if ($KindID[$i]['ROW_NUMBER'] == $one['ROW_NUMBER']) {
//                    $KindID[$i]['Codes'] = $one['Code'];
//                }
//            }
//            $Family2[] =  ['AUID' => $UserID, 'Code' => $KindID[$i]['Codes'], 'Caption' => '[金币场].[' .$KindID[$i]['KindName']. '].'.$Agent['Compellation'].'的亲友团', 'KindID' => $KindID[$i]['KindID'], 'State' => 1,'FamilyType'=>2];
//        }
//        $inserfamily2 = table('Family', 'rydb.websms')->insertAll($Family2,true);
//        if ( $inserfamily2 != $Num) {
//            return result([], 13,'亲友团增加失败');
//        }
//
//        /*
//         * 添加房间绑定
//         * */
//
//        $Users = table('Family', 'rydb.websms')->where(['AUID'=>$UserID,'FamilyType'=>2])->select();
//        foreach ($Users as $v) {
//          $data[] = table('CodeIdentifier', 'rydb.websms')->where('Code', $v['Code'])->find();
//        }
//        for ($i = 0; $i < count($data); $i++) {
//            foreach ($Users as $one) {
//                if ($data[$i]['Code'] == $one['Code']) {
//                    $insertcodeidentifier = table('CodeIdentifier', 'rydb.websms')->where('Code', $one['Code'])->update(['FamilyUsed' => $one['ID']]);
//                }
//            }
//        }
//        if (!$insertcodeidentifier) {
//            return result([], 14,'房间绑定失败');
//        }
//
//        /*
//         * 增加房间权限
//         * */
//        $Users = table('Family', 'rydb.websms')->where(['AUID'=>$UserID,'FamilyType'=>2])->select();
//        foreach ($Users as $v) {
//            $FamilyMember[] =   ['FamilyID' => $v['ID'], 'MemberUID' => $v['AUID'], 'Status' => 1, 'UserRight' => 64, 'IsBlack' => 0, 'IsPass' => 1, 'Gold' => 0];
//
//        }
//        $inserfamilymember = table('FamilyMember', 'rydb.websms')->insertAll($FamilyMember,true);
//        if (!$inserfamilymember) {
//            return result([], 15,'房间权限绑定失败');
//        }
//
//    }


    /**
     *  @brief  : 推广员注册-补发短信
     *  @return : json
     *  @details:
     */
    public function sendAction() {
        $id = $this->request->param('id/d', 0);
        if ($id <= 0) {
            return result([], 1, '业务参数非法');
        }
        $rs = table('CYWebSMSDB.dbo.AgentReg a', 'rydb.websms')->field([
            'UserID', 'GameID', 'Compellation', 'MobilePhone', 'LogonPass',
        ])->where('ID', $id)->find();
        if (empty($rs)) {
            return result([], 1, '不存在该记录');
        }
        // $msg = "【XXX】您的推广员申请已经通过, 推广员ID:{$rs['GameID']}(邀请码), 登陆密码:{$rs['LogonPass']}";
        // var_dump($rs, $msg);
        // $a = \org\sms253::send('15925612848', $msg);
        // '20180803203703,108'
        // '20180803203807,0,1000803203807881600'
        // var_dump($a);
        //
        return result([], 0, "补发短信成功！{$rs['MobilePhone']}");
    }
    /**
     *  @brief  : 推广员注册-删除该推广员
     *  @return : json
     *  @details:
     **/
    public function delagentAction(){
        $uid = $this->request->param('UserID/d',0);
        $channel = $this->request->param('channel/d',0);
        $adminid = session(config('auth.session'));
        $addip = request()->ip();
        $pdo = table('', 'rydb.websms')->query("EXEC [dbo].[PHP_DeleteAgent] @dwUserID = {$uid},@dwAdminID = {$adminid},@dwChannel = {$channel},@szAddIp= '"."{$addip}"."'", [], false, true);
        do {
            $result = $pdo->fetchAll(\PDO::FETCH_ASSOC);
        } while ($pdo->nextRowset());
        if ($result['err'] = 'success'){
            return result([],0 ,'');
        }else{
            return result([],101,$result['err']);
        }

    }
    /**
     *  @brief  : 推广员注册-重置密码
     *  @return : JSON
     *  @details:
     */
    public function resetpwdAction() {
        if (!$this->request->isPost()) {
            return result([], 100, '非法请求');
        }
        $id = $this->request->param('id/d', 0);
        if ($id <= 0) {
            return result([], 101, '业务参数非法');
        }
        $oldPwd = table('AgentReg', 'rydb.websms')->where(['ID' => $id])->value('LogonPass');
        $newPwd = substr(str_replace('.', '', strval(microtime(true))), -6, 6); // 随机6位数字
        $eax = table('AgentReg', 'rydb.websms')->where(['ID' => $id])->setField('LogonPass', $newPwd);
        trace("代理密码被后台修改[{$id}], 旧密码: `{$oldPwd}`, 新密码: `{$newPwd}`");
        return result([], 0, '');
    }
    /**
     *  @brief  : 推广员结算记录
     *  @return : page
     *  @details:
     */
    public function rebateAction() {
        $conds = [];
        $order = [];
        $AGENT_TYPE = GetAgentType();
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['g.Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['g.Channel'][] = ['EQ', $channel];
        } else {
            $conds['g.Channel'] = ['IN', array_keys($CHANNELS)];
        }
        ////////////////////////////////////////
        $AgentType = $this->request->param('AgentType/d', -1);
        $AgentType = array_key_exists($AgentType, $AGENT_TYPE) ? $AgentType : -1;
        if ($AgentType > 0) {
            $conds['b.AgentType'] = $AgentType;
        }
        ////////////////////////////////////////
        $search = $this->request->param('search/s', '', 'trim');
        if (!empty($search)) {
            if (is_numeric($search) && $search > 0 && $search < PHP_INT_MAX) {
                $conds['a.ID|a.UserID|b.GameID'] = $search;
            } else {
                $conds['b.Compellation'] = ['LIKE', "%{$search}%"];
            }
        }
        ////////////////////////////////////////
        $time1 = $this->request->param('time1/s', '', 'trim');
        $time2 = $this->request->param('time2/s', '', 'trim');

        $aa = YmdHis2Unix($time1);
        $bb = YmdHis2Unix($time2);
        $ta = date('Y-m-d 00:00:00', $aa);
        $tb = date('Y-m-d 23:59:59', $bb);
        if ($aa > 0) {
            if ($bb > 0) {
                if ($aa <= $bb) {
                    $conds['a.CollectDate'] = ['BETWEEN TIME', [$ta, $tb]];
                } else {
                    $conds['a.CollectDate'] = ['>= TIME', $ta];
                }
            } else {
                $conds['a.CollectDate'] = ['>= TIME', $ta];
            }
        } else {
            if ($bb > 0) {
                $conds['a.CollectDate'] = ['<= TIME', $tb];
            }
        }
        ////////////////////////////////////////
        $orderMap = [
            'A' => 'Channel',
            'B' => 'AgentType',
            'C' => 'UserID',
            'D' => 'GameID',
            'E' => 'RegisterDate',
            'F' => 'AgentLevel',
            'G' => 'RMB',
            'H' => 'CollectDate',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'B';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        ////////////////////////////////////////
        $list = table('CYWebSMSDB.dbo.AgentRebate a', 'rydb.websms')->field([
            'a.CollectDate', 'a.ID', 'a.RMB', 'a.UserID', 'b.Compellation', 'b.GameID', 'b.AgentLevel', 'g.AccountImgUrl', 'g.Channel', 'g.RegisterDate', 'g.AccountsType', 'b.AgentType',
            '( SELECT TOP 1 [e].[CollectDate] FROM [CYWebSMSDB].[dbo].[AgentRebate] e WHERE [e].[UserID] = [a].[UserID] AND [e].[CollectDate] < [a].[CollectDate] ORDER BY [e].[CollectDate] DESC ) AS CollectDate1',
            "( CASE b.IsDirect WHEN 1 THEN '直销' ELSE ( CASE b.AgentLevel WHEN 1 THEN '一级' WHEN 2 THEN '二级' WHEN 3 THEN '三级' WHEN 4 THEN '四级' WHEN 5 THEN '五级' WHEN 6 THEN '六级' WHEN 7 THEN '七级' ELSE '默认' END ) END )"=>'AgentLevelName',
        ])
            ->join('CYWebSMSDB.dbo.AgentReg b',  'b.UserID = a.UserID', 'LEFT')
            ->join('CYBasicDB.dbo.AccountsInfo g', 'g.UserID = b.UserID', 'LEFT')
            ->where($conds)->order($order)->paginate();
        ////////////////////////////////////////
        $totalRMB = table('CYWebSMSDB.dbo.AgentRebate a', 'rydb.websms')
            ->join('CYWebSMSDB.dbo.AgentReg b',  'b.UserID = a.UserID', 'LEFT')
            ->join('CYBasicDB.dbo.AccountsInfo g', 'g.UserID = b.UserID', 'LEFT')
            ->where($conds)->sum('a.RMB');
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'AgentType' => $AgentType,
            'AGENT_TYPE'=> $AGENT_TYPE,
            'CHANNELS'  => $CHANNELS,
            'channel'   => $channel,
            'list'    => $list,
            'time1'   => $time1,
            'time2'   => $time2,
            'search'  => $search,
            'totalRMB'=> $totalRMB,
        ]);
    }

    /**
     *  @brief  : 玩家解绑查询
     *  @return : page
     *  @details:
     */
    public function unbindAction() {
        $conds = [];
        $order = [];
        $CHANNELS = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['b.Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['b.Channel'][] = ['EQ', $channel];
        } else {
            $conds['b.Channel'] = ['IN', array_keys($CHANNELS)];
        }
        $search = $this->request->param('search/s', '', 'trim');
        if (!empty($search)) {
            if (is_numeric($search) && $search > 0 && $search < PHP_INT_MAX) {
                $search = $this->request->param('search/d', 0);
                if ($search > 0) {
                    $conds['b.GameID|b.UserID'] = $search;
                }
            } else {
                $conds['b.NickName'] = ['LIKE', "%{$search}%"];
            }
        }
        ////////////////////////////////////////////////
        $time1 = $this->request->param('time1/s', '', 'trim');
        $time2 = $this->request->param('time2/s', '', 'trim');
        $aa = YmdHis2Unix($time1);
        $bb = YmdHis2Unix($time2);
        $ta = YmdHis($aa);
        $tb = YmdHis($bb);
        if ($aa > 0) {
            if ($bb > 0) {
                if ($aa <= $bb) {
                    $conds['a.UpdateTime'] = ['BETWEEN TIME', [$ta, $tb]];
                } else {
                    $conds['a.UpdateTime'] = ['>= TIME', $ta];
                }
            } else {
                $conds['a.UpdateTime'] = ['>= TIME', $ta];
            }
        } else {
            if ($bb > 0) {
                $conds['a.UpdateTime'] = ['<= TIME', $tb];
            }
        }
        ////////////////////////////////////////////////////////////////////////////
        $orderMap = [
            'B' => 'Channel',
            'C' => 'GameID',
            'D' => 'RoomCard',
            'E' => 'PayALL',
            'F' => 'SpreaderID',
            'G' => 'BindCode',
            'H' => 'UpdateTime',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'H';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        ////////////////////////////////////////////////////////////////////////////
        $list = table('CYRecordDB.dbo.RecordRemoveBindCode a', 'rydb.record')->field([
            'a.UpdateTime', "ISNULL(c.HeadImgUrl, '')"=>'HeadImgUrl', 'b.NickName', 'b.GameID', 'b.UserID',
            'b.Gender', 'b.AccountsType', 'b.Channel', 'b.SpreaderIDBindTime'=>'BindTime', 'd.RoomCard',
            'b.SpreaderID', 'e.GameID' => 'BindCode', 'e.Compellation'=> 'ACompellation',
            'e.AgentLevel', 'e.IsDirect', 'e.DirectLevel', 'b.Accounts', 'b.Compellation',
            'b.PassPortID', 'c.MobilePhone', 'b.RegisterDate', 'b.RegisterIP', 'b.GameLogonTimes',
            'b.LastLogonDate', 'b.LastLogonIP',
            '(SELECT ISNULL(SUM(g.RMB), 0) FROM CYWebSMSDB.dbo.ChargeOnline g WHERE g.UserID = a.UserID AND g.[Status] = 1 AND g.[GameStatus] = 1)' => 'PayALL',
        ])
            ->join('CYBasicDB.dbo.AccountsInfo b', 'a.UserID = b.UserID', 'LEFT')
            ->join('CYBasicDB.dbo.IndividualDatum c', 'a.UserID = c.UserID', 'LEFT')
            ->join('RYTreasureDB.dbo.UserRoomCard d', 'a.UserID = d.UserID', 'LEFT')
            ->join('CYWebSMSDB.dbo.AgentReg e', 'b.SpreaderID = e.UserID AND b.SpreaderID > 0', 'LEFT')
            ->where($conds)->order($order)->paginate();
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'search'=> $search,
            'time1' => $time1,
            'time2' => $time2,
            'list'  => $list,
            'channel'   => $channel,
            'CHANNELS'  => $CHANNELS,
        ]);
    }
}
